import React, { useState } from "react";
import { Menu } from "antd";
import { useNavigate, useLocation } from "react-router-dom";
import styles from "./index.module.scss";

const items: any = [
  {
    label: "QUERY",
    key: "/dataQuery",
  },
  {
    label: "NOOE GUIDANCE",
    key: "/nodeGuidance",
  },
  {
    label: "MONITOR",
    key: "/monitor",
  },
  {
    label: "NEWS",
    key: "/news",
  },
];

const MainMenu: React.FC = () => {
  // const [dataSource, setDataSource]: any = useState([]);
  // useEffect(() => {
  //   axios.get("/test/rights").then((res) => {
  //     const list = res.data;
  //     setDataSource(list);
  //   });
  // }, []);

  // const token: any = localStorage.getItem("token");
  // const res = JSON.parse(token);
  // const { roleId } = res;
  // const [permissions, setPermissions]: any = useState([]);
  // useEffect(() => {
  //   axios.get(`/test/roles?roleType=${roleId}`).then((res) => {
  //     setPermissions(res.data[0].rights);
  //   });
  // }, [roleId]);

  // // 判断用户是否有权限查看某项菜单
  // const hasPermission = (key: string) => {
  //   return permissions.includes(key);
  // };
  // // 根据用户角色和权限动态生成菜单项
  // const filteredItems = dataSource.filter((item: any) => {
  //   if (item.pagepermission !== 1) return false;
  //   return hasPermission(item.key);
  // });

  const navigateto = useNavigate();
  const currentRoute = useLocation();
  const menuClick = (e: { key: string }) => {
    // 点击跳转到对应路由  编程式导航跳转 利用到一个hook
    navigateto(e.key);
  };

  //拿着currentRoute.pathname跟items数组的每一项的children的key值进行对比，如果找到了相等了，
  //就要他上一级的key,这个key给到openkeys数组的元素，作为初始值
  let firstOpenKey: string = "";
  //在这里进行对比  find
  function findKey(obj: { key: string }) {
    return obj.key === currentRoute.pathname;
  }
  for (let i = 0; i < items.length; i++) {
    // 判断找不找得到
    if (
      items[i]!["children"] &&
      items[i]!["children"].length > 0 &&
      items[i]!["children"].find(findKey)
      // &&
      // hasPermission(dataSource[i]!.key as string)
    ) {
      firstOpenKey = items[i]!.key as string;
      break;
    }
  }

  const [openKeys, setOpenKeys] = useState([firstOpenKey]);
  const handleOpenChange = (keys: string[]) => {
    // console.log(keys);  //keys是一个数组，记录当前哪一项是展开的(用key来记录)
    // 把这个数组修改成最后一项，因为我只要一项是展开的，就是我刚刚点击的这一项
    setOpenKeys([keys[keys.length - 1]]);
  };

  return (
    // <div style={{ display: "flex", width: "100%" }}>
    <Menu
      theme="dark"
      style={{ backgroundColor: "rgba(255, 255, 255, 0.1)", color: "#fff" }}
      // defaultSelectedKeys 表示当前样式所在的选中项的key
      defaultSelectedKeys={[currentRoute.pathname]}
      selectedKeys={[currentRoute.pathname]}
      mode="horizontal"
      // items={filteredItems}
      items={items}
      onClick={menuClick}
      // 某项菜单展开和回收的事件
      onOpenChange={handleOpenChange}
      // 当前菜单展开项的key数组
      openKeys={openKeys}
    />
    // </div>
  );
};
export default MainMenu;
